package com.example.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;


@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, ControllerAdvice.class})
public class GlobalExceptionHandler {

    /**
     * 全局异常捕获
     *
     * */

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.info(exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")){
            String[] str = exception.getMessage().split(" ");
            String message =  "用户" + str[2]+ "已存在";
            return R.error(message);
        }
        return R.error("Error!");
    }


    /**
     * 全局捕获自定义业务异常
     *
     * */

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        log.info(exception.getMessage());
        return R.error(exception.getMessage());
    }

}
